package fun.tan90.easy.binlog.plugin.redis.sentinel.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.listener.CaffeineRemovalListener;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.redis.sentinel.listener.RedisSentinelEventProcessor;
import fun.tan90.easy.binlog.plugin.redis.sentinel.service.impl.RedisSentinelPluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.JedisSentinelPool;

import java.util.concurrent.TimeUnit;

/**
 * description
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/07/13 13:02
 */
@Slf4j
public class RedisSentinelPluginAutoConfiguration {

    public RedisSentinelPluginAutoConfiguration() {
        log.info("init RedisSentinelPlugin");
    }

    @Bean
    public RedisSentinelCacheLoader redisSentinelPoolCacheLoader() {
        return new RedisSentinelCacheLoader();
    }

    @Bean
    public LoadingCache<String, JedisSentinelPool> redisSentinelPoolCache(RedisSentinelCacheLoader redisSentinelCacheLoader) {
        return Caffeine.newBuilder()
                .maximumSize(10_000)
                .removalListener(new CaffeineRemovalListener(OutputTypeEnum.REDIS_SENTINEL.getOutput()))
                .expireAfterAccess(1, TimeUnit.DAYS)
                .build(redisSentinelCacheLoader);
    }

    @Bean
    public RedisSentinelEventProcessor redisSentinelEventProcessor(LoadingCache<String, JedisSentinelPool> redisSentinelPoolCache) {
        return new RedisSentinelEventProcessor(redisSentinelPoolCache);
    }

    @Bean(name = "redis-sentinel")
    public PluginService redisSentinelPluginService() {
        return new RedisSentinelPluginService();
    }
}